<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部导航栏 -->
    <nav class="bg-white shadow-lg border-b border-gray-200 fixed w-full top-0 z-50">
      <div class="px-6 py-4">
        <div class="flex justify-between items-center">
          <div class="flex items-center space-x-4">
            <div class="flex items-center space-x-3">
              <div class="w-10 h-10 bg-gradient-to-br from-blue-600 to-purple-600 rounded-lg flex items-center justify-center">
                <i class="fas fa-industry text-white text-lg"></i>
              </div>
              <div>
                <h1 class="text-xl font-bold text-gray-800">工业管道安全巡检系统</h1>
                <p class="text-xs text-gray-500">Industrial Pipeline Safety Inspection System</p>
              </div>
            </div>
            <div class="hidden lg:block h-6 w-px bg-gray-300 ml-6"></div>
            <div class="hidden lg:flex items-center space-x-2 text-sm text-gray-600">
              <i class="fas fa-map-marker-alt text-blue-500"></i>
              <span>石化园区A区管理中心</span>
            </div>
          </div>
          <div class="flex items-center space-x-4">
            <div class="hidden md:block relative">
              <input type="text" 
                     v-model="searchQuery"
                     @input="handleSearch"
                     @focus="showSearchResults = true"
                     @blur="hideSearchResults"
                     placeholder="搜索任务、线路、人员..." 
                     class="w-80 pl-10 pr-4 py-2 bg-gray-100 border-0 rounded-lg focus:ring-2 focus:ring-blue-500 focus:bg-white transition"/>
              <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
              
              <!-- 搜索结果下拉框 -->
              <div v-if="showSearchResults && searchResults.length > 0" 
                   class="absolute top-full left-0 right-0 mt-1 bg-white border border-gray-200 rounded-lg shadow-lg z-50 max-h-80 overflow-y-auto">
                <div v-for="result in searchResults" :key="result.id" 
                     @click="handleSearchResultClick(result)"
                     class="p-3 hover:bg-gray-50 cursor-pointer border-b border-gray-100 last:border-b-0">
                  <div class="flex items-center space-x-3">
                    <i :class="result.icon" class="text-blue-500"></i>
                    <div>
                      <p class="font-medium text-gray-800">{{ result.title }}</p>
                      <p class="text-sm text-gray-500">{{ result.description }}</p>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 无搜索结果提示 -->
              <div v-if="showSearchResults && searchQuery && searchResults.length === 0" 
                   class="absolute top-full left-0 right-0 mt-1 bg-white border border-gray-200 rounded-lg shadow-lg z-50 p-4">
                <p class="text-gray-500 text-center">未找到相关结果</p>
              </div>
            </div>
            <div class="relative">
              <button class="p-2 text-gray-600 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition relative">
                <i class="fas fa-bell text-xl"></i>
                <span class="absolute -top-1 -right-1 w-5 h-5 bg-red-500 text-white text-xs rounded-full flex items-center justify-center">8</span>
              </button>
            </div>
            <button class="p-2 text-gray-600 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition">
              <i class="fas fa-envelope text-xl"></i>
            </button>
            <div class="flex items-center space-x-3 pl-4 border-l border-gray-200">
              <img :src="getUserAvatar()" 
                   @error="handleAvatarError"
                   class="w-10 h-10 rounded-full border-2 border-gray-200 object-cover"/>
              <div class="hidden lg:block">
                <p class="text-sm font-semibold text-gray-800">{{ authStore.userInfo?.name || '管理员' }}</p>
                <p class="text-xs text-gray-500">{{ authStore.userInfo?.roleName || '系统管理员' }}</p>
              </div>
              <div class="relative">
                <button @click="handleUserMenuClick('profile')" class="text-gray-400 hover:text-gray-600">
                  <i class="fas fa-chevron-down"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </nav>

    <div class="flex pt-20">
      <!-- 侧边栏 -->
      <aside class="w-72 min-h-screen shadow-2xl fixed sidebar-gradient">
        <div class="p-6 text-white">
          <div class="mb-8 flex items-center space-x-3">
            <div class="w-12 h-12 bg-white/20 rounded-xl flex items-center justify-center">
              <i class="fas fa-tachometer-alt text-white text-xl"></i>
            </div>
            <div>
              <h2 class="font-bold text-lg">控制台</h2>
              <p class="text-blue-200 text-sm">管理中心</p>
            </div>
          </div>
          <nav class="space-y-2">
            <div class="text-blue-200 text-xs font-semibold uppercase tracking-wider mb-4">主要功能</div>
            <RouterLink to="/admin/dashboard" class="sidebar-item flex items-center px-4 py-3 text-blue-100 hover:text-white rounded-xl" :class="{ active: isActive('/admin/dashboard') }">
              <i class="fas fa-tachometer-alt w-6 text-lg"></i>
              <span class="ml-3 font-medium">主控制台</span>
            </RouterLink>
            <RouterLink to="/admin/lines" class="sidebar-item flex items-center px-4 py-3 text-blue-100 hover:text-white rounded-xl" :class="{ active: isActive('/admin/lines') }">
              <i class="fas fa-route w-6 text-lg"></i>
              <span class="ml-3 font-medium">线路管理</span>
            </RouterLink>
            <RouterLink to="/admin/inspection" class="sidebar-item flex items-center px-4 py-3 text-blue-100 hover:text-white rounded-xl" :class="{ active: isActive('/admin/inspection') }">
              <i class="fas fa-clipboard-check w-6 text-lg"></i>
              <span class="ml-3 font-medium">巡检管理</span>
            </RouterLink>
            <RouterLink to="/admin/defects" class="sidebar-item flex items-center px-4 py-3 text-blue-100 hover:text-white rounded-xl" :class="{ active: isActive('/admin/defects') }">
              <i class="fas fa-exclamation-triangle w-6 text-lg"></i>
              <span class="ml-3 font-medium">缺陷管理</span>
            </RouterLink>
            <RouterLink to="/admin/remedies" class="sidebar-item flex items-center px-4 py-3 text-blue-100 hover:text-white rounded-xl" :class="{ active: isActive('/admin/remedies') }">
              <i class="fas fa-tools w-6 text-lg"></i>
              <span class="ml-3 font-medium">消缺管理</span>
            </RouterLink>
            <div class="text-blue-200 text-xs font-semibold uppercase tracking-wider mt-8 mb-4">数据分析</div>
            <RouterLink to="/admin/statistics" class="sidebar-item flex items-center px-4 py-3 text-blue-100 hover:text-white rounded-xl" :class="{ active: isActive('/admin/statistics') }">
              <i class="fas fa-chart-bar w-6 text-lg"></i>
              <span class="ml-3 font-medium">统计报表</span>
            </RouterLink>
          </nav>
        </div>
      </aside>

      <!-- 主内容区 -->
      <main class="flex-1 ml-72 p-8 bg-gray-50 w-full">
        <router-view />
      </main>
    </div>
  </div>
</template>

<script setup>
import { useRoute, RouterLink, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useAppStore } from '@/stores/app'
import { ElMessageBox, ElMessage } from 'element-plus'
import { onMounted, onUnmounted, ref } from 'vue'
import { lineAPI, inspectionAPI, defectAPI, remedyAPI } from '@/api/modules'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()
const appStore = useAppStore()

let tokenCheckInterval = null

// 搜索相关状态
const searchQuery = ref('')
const searchResults = ref([])
const showSearchResults = ref(false)
const searchTimeout = ref(null)

// 默认头像
const defaultAvatar = 'https://ui-avatars.com/api/?name=Admin&background=3b82f6&color=ffffff&size=40&bold=true'

const isActive = (path) => route.path.startsWith(path)

/**
 * 获取用户头像
 */
const getUserAvatar = () => {
  return authStore.userInfo?.avatar || defaultAvatar
}

/**
 * 处理头像加载错误
 */
const handleAvatarError = (event) => {
  event.target.src = defaultAvatar
}

// 检查token过期状态
const checkTokenExpiry = () => {
  if (authStore.isLoggedIn) {
    const remainingTime = authStore.getRemainingTime()
    
    // 如果剩余时间少于5分钟，提醒用户
    if (remainingTime <= 5 && remainingTime > 0) {
      ElMessage.warning(`登录即将过期，剩余 ${remainingTime} 分钟`)
    }
    
    // 如果token已过期，自动登出
    if (authStore.isTokenExpired()) {
      ElMessage.error('登录已过期，请重新登录')
      authStore.logout()
    }
  }
}

// 启动定时检查
onMounted(() => {
  // 每30秒检查一次token状态
  tokenCheckInterval = setInterval(checkTokenExpiry, 30000)
  
  // 立即检查一次
  checkTokenExpiry()
})

// 清理定时器
onUnmounted(() => {
  if (tokenCheckInterval) {
    clearInterval(tokenCheckInterval)
  }
})

/**
 * 处理登出
 */
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要退出登录吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    authStore.logout()
    // 路由跳转会在路由守卫中处理
  } catch (error) {
    // 用户取消
  }
}

/**
 * 处理搜索输入
 */
const handleSearch = () => {
  if (searchTimeout.value) {
    clearTimeout(searchTimeout.value)
  }
  
  if (searchQuery.value.trim().length < 2) {
    searchResults.value = []
    return
  }
  
  // 防抖处理，500ms后执行搜索
  searchTimeout.value = setTimeout(async () => {
    await performSearch(searchQuery.value.trim())
  }, 500)
}

/**
 * 执行搜索
 */
const performSearch = async (query) => {
  try {
    const results = []
    
    // 搜索线路
    try {
      const lineResponse = await lineAPI.getLines({ keyword: query, pageNum: 1, pageSize: 5 })
      if (lineResponse.code === 0 && lineResponse.data?.list) {
        lineResponse.data.list.forEach(line => {
          results.push({
            id: `line_${line.id}`,
            type: 'line',
            title: line.name || line.code,
            description: `线路编码: ${line.code} | 长度: ${line.lengthKm}km`,
            icon: 'fas fa-route',
            data: line
          })
        })
      }
    } catch (error) {
      console.log('搜索线路失败:', error)
    }
    
    // 搜索巡检任务
    try {
      const taskResponse = await inspectionAPI.getTasks({ keyword: query, pageNum: 1, pageSize: 5 })
      if (taskResponse.code === 0 && taskResponse.data?.list) {
        taskResponse.data.list.forEach(task => {
          results.push({
            id: `task_${task.id}`,
            type: 'task',
            title: task.name || task.code,
            description: `任务状态: ${getStatusText(task.status)} | 负责人: ${task.assigneeName || '未分配'}`,
            icon: 'fas fa-clipboard-check',
            data: task
          })
        })
      }
    } catch (error) {
      console.log('搜索任务失败:', error)
    }
    
    // 搜索缺陷
    try {
      const defectResponse = await defectAPI.getDefects({ keyword: query, pageNum: 1, pageSize: 5 })
      if (defectResponse.code === 0 && defectResponse.data?.list) {
        defectResponse.data.list.forEach(defect => {
          results.push({
            id: `defect_${defect.id}`,
            type: 'defect',
            title: defect.description || defect.code,
            description: `缺陷等级: ${defect.levelName} | 状态: ${getDefectStatusText(defect.status)}`,
            icon: 'fas fa-exclamation-triangle',
            data: defect
          })
        })
      }
    } catch (error) {
      console.log('搜索缺陷失败:', error)
    }
    
    // 搜索消缺任务
    try {
      const remedyResponse = await remedyAPI.getRemedies({ keyword: query, pageNum: 1, pageSize: 5 })
      if (remedyResponse.code === 0 && remedyResponse.data?.list) {
        remedyResponse.data.list.forEach(remedy => {
          results.push({
            id: `remedy_${remedy.id}`,
            type: 'remedy',
            title: remedy.description || remedy.taskNo,
            description: `任务编号: ${remedy.taskNo} | 负责人: ${remedy.assigneeName || '未分配'}`,
            icon: 'fas fa-tools',
            data: remedy
          })
        })
      }
    } catch (error) {
      console.log('搜索消缺任务失败:', error)
    }
    
    searchResults.value = results.slice(0, 10) // 最多显示10个结果
  } catch (error) {
    console.error('搜索失败:', error)
    searchResults.value = []
  }
}

/**
 * 处理搜索结果点击
 */
const handleSearchResultClick = (result) => {
  showSearchResults.value = false
  searchQuery.value = ''
  
  // 根据结果类型跳转到相应页面
  switch (result.type) {
    case 'line':
      router.push('/admin/lines')
      break
    case 'task':
      router.push('/admin/inspection')
      break
    case 'defect':
      router.push('/admin/defects')
      break
    case 'remedy':
      router.push('/admin/remedies')
      break
  }
  
  ElMessage.success(`已跳转到${getTypeName(result.type)}页面`)
}

/**
 * 隐藏搜索结果
 */
const hideSearchResults = () => {
  // 延迟隐藏，让点击事件能够正常触发
  setTimeout(() => {
    showSearchResults.value = false
  }, 200)
}

/**
 * 获取状态文本
 */
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待处理',
    'in_progress': '进行中',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || status || '未知状态'
}

/**
 * 获取缺陷状态文本
 */
const getDefectStatusText = (status) => {
  const statusMap = {
    'pending': '待处理',
    'in_progress': '处理中',
    'resolved': '已解决',
    'closed': '已关闭'
  }
  return statusMap[status] || status || '未知状态'
}

/**
 * 获取类型名称
 */
const getTypeName = (type) => {
  const typeMap = {
    'line': '线路管理',
    'task': '巡检管理',
    'defect': '缺陷管理',
    'remedy': '消缺管理'
  }
  return typeMap[type] || '未知类型'
}

/**
 * 处理用户菜单点击
 */
const handleUserMenuClick = (action) => {
  switch (action) {
    case 'profile':
      router.push('/admin/profile')
      break
    case 'settings':
      ElMessage.info('系统设置功能开发中')
      break
    case 'logout':
      handleLogout()
      break
  }
}
</script>

<style scoped>
.sidebar-gradient {
  background: linear-gradient(180deg, #1e3a8a 0%, #1e40af 50%, #2563eb 100%);
}
.sidebar-item { transition: all .2s ease; }
.sidebar-item:hover { background: rgba(255,255,255,.1); transform: translateX(4px); }
.sidebar-item.active { background: rgba(255,255,255,.15); border-left: 4px solid #fbbf24; }
</style>
